// 立即生效的游戏增强 - 确保能看到效果
(function() {
    'use strict';
    
    console.log('⚡ 立即效果系统启动...');
    
    // 立即显示加载信息
    setTimeout(() => {
        console.log('🎮 立即效果系统 - 3秒后激活');
        
        // 在页面上显示提示
        const notify = document.createElement('div');
        notify.style.cssText = `
            position: fixed; top: 10px; left: 50%; transform: translateX(-50%);
            background: rgba(0, 0, 0, 0.8); color: #00FF00; padding: 10px 20px;
            border-radius: 5px; z-index: 10000; font-family: monospace;
            border: 2px solid #00FF00;
        `;
        notify.textContent = '🎮 游戏增强系统正在加载...';
        document.body.appendChild(notify);
        
        setTimeout(() => {
            if (notify.parentNode) {
                notify.textContent = '✅ 增强系统已激活 - 按空格闪避';
                notify.style.borderColor = '#FFD700';
                notify.style.color = '#FFD700';
                
                setTimeout(() => {
                    notify.style.opacity = '0';
                    setTimeout(() => {
                        if (notify.parentNode) document.body.removeChild(notify);
                    }, 2000);
                }, 3000);
            }
        }, 3000);
        
    }, 1000);
    
    // 立即设置的功能
    class InstantEffects {
        constructor() {
            this.active = false;
            this.dodgeCooldown = 0;
            this.comboCount = 0;
            this.lastKillTime = 0;
            this.environmentObjects = [];
            
            this.initialize();
        }
        
        initialize() {
            console.log('🚀 立即效果初始化开始');
            
            // 立即设置闪避
            this.setupDodgeImmediate();
            
            // 立即设置连击显示
            this.setupComboDisplay();
            
            // 延迟设置需要游戏引擎的功能
            setTimeout(() => {
                this.setupGameIntegration();
            }, 4000);
            
            this.active = true;
            console.log('✅ 立即效果初始化完成');
        }
        
        setupDodgeImmediate() {
            console.log('🏃 立即设置闪避功能');
            
            document.addEventListener('keydown', (e) => {
                if (e.code === 'Space') {
                    e.preventDefault();
                    this.performDodge();
                }
            });
            
            // 显示闪避状态
            this.createStatusDisplay();
        }
        
        createStatusDisplay() {
            const statusDiv = document.createElement('div');
            statusDiv.id = 'enhancementStatus';
            statusDiv.style.cssText = `
                position: fixed; top: 80px; right: 20px; z-index: 9999;
                background: rgba(0, 0, 0, 0.7); color: white; padding: 10px;
                border-radius: 5px; font-family: monospace; font-size: 12px;
                border: 1px solid #4ECDC4; min-width: 150px;
            `;
            statusDiv.innerHTML = `
                <div style="color: #4ECDC4; font-weight: bold; margin-bottom: 5px;">🎮 增强状态</div>
                <div id="dodgeStatus">🏃 闪避: 准备就绪</div>
                <div id="comboStatus">🔥 连击: 0x</div>
                <div style="color: #999; font-size: 10px; margin-top: 5px;">按空格闪避</div>
            `;
            
            document.body.appendChild(statusDiv);
            
            // 定期更新状态
            setInterval(() => {
                this.updateStatusDisplay();
            }, 100);
        }
        
        updateStatusDisplay() {
            const dodgeStatus = document.getElementById('dodgeStatus');
            const comboStatus = document.getElementById('comboStatus');
            
            if (dodgeStatus) {
                if (this.dodgeCooldown > 0) {
                    dodgeStatus.innerHTML = `🏃 闪避: ${(this.dodgeCooldown / 1000).toFixed(1)}s`;
                    dodgeStatus.style.color = '#FF6B6B';
                } else {
                    dodgeStatus.innerHTML = '🏃 闪避: 准备就绪';
                    dodgeStatus.style.color = '#4ECDC4';
                }
            }
            
            if (comboStatus) {
                let color = '#FFFFFF';
                if (this.comboCount >= 10) color = '#FFD700';
                else if (this.comboCount >= 5) color = '#00FF00';
                
                comboStatus.innerHTML = `🔥 连击: ${this.comboCount}x`;
                comboStatus.style.color = color;
            }
            
            // 更新冷却时间
            if (this.dodgeCooldown > 0) {
                this.dodgeCooldown -= 100;
            }
        }
        
        performDodge() {
            if (this.dodgeCooldown > 0) {
                console.log('🚫 闪避冷却中');
                return;
            }
            
            console.log('🏃 执行闪避！');
            this.dodgeCooldown = 1000;
            
            // 立即显示闪避效果
            this.showDodgeEffect();
            
            // 如果玩家存在，给予短暂无敌
            if (window.player) {
                window.player.invulnerable = true;
                setTimeout(() => {
                    if (window.player) window.player.invulnerable = false;
                }, 300);
            }
        }
        
        showDodgeEffect() {
            // 创建视觉闪烁效果
            const flash = document.createElement('div');
            flash.style.cssText = `
                position: fixed; top: 0; left: 0; width: 100%; height: 100%;
                background: rgba(255, 255, 255, 0.3); pointer-events: none;
                z-index: 5000; animation: dodgeFlash 0.3s ease-out;
            `;
            
            const style = document.createElement('style');
            style.textContent = `
                @keyframes dodgeFlash {
                    0% { opacity: 0.5; }
                    50% { opacity: 0.2; }
                    100% { opacity: 0; }
                }
            `;
            document.head.appendChild(style);
            document.body.appendChild(flash);
            
            setTimeout(() => {
                if (flash.parentNode) document.body.removeChild(flash);
                if (style.parentNode) document.head.removeChild(style);
            }, 300);
            
            // 粒子效果 (如果游戏引擎可用)
            if (window.gameEngine && window.player) {
                for (let i = 0; i < 8; i++) {
                    window.gameEngine.particles.push({
                        x: window.player.x + (Math.random() - 0.5) * 30,
                        y: window.player.y + (Math.random() - 0.5) * 30,
                        vx: (Math.random() - 0.5) * 150,
                        vy: (Math.random() - 0.5) * 150,
                        life: 0.5,
                        maxLife: 0.5,
                        color: '#FFFFFF',
                        size: Math.random() * 5 + 2
                    });
                }
            }
        }
        
        setupComboDisplay() {
            console.log('🔥 设置连击显示');
            
            // 监控连击
            setInterval(() => {
                this.updateCombo();
            }, 100);
        }
        
        updateCombo() {
            const now = Date.now();
            
            // 检查连击超时
            if (this.comboCount > 0 && now - this.lastKillTime > 3000) {
                this.comboCount = 0;
            }
        }
        
        addKill() {
            const now = Date.now();
            
            if (now - this.lastKillTime > 3000) {
                this.comboCount = 1;
            } else {
                this.comboCount++;
            }
            
            this.lastKillTime = now;
            
            console.log(`🔥 击杀连击: ${this.comboCount}x`);
            
            // 显示连击效果
            this.showComboEffect();
            
            // 连击奖励
            if (this.comboCount % 5 === 0) {
                this.giveComboReward();
            }
        }
        
        showComboEffect() {
            if (!window.player) return;
            
            // 屏幕中央显示连击
            const comboDisplay = document.createElement('div');
            comboDisplay.style.cssText = `
                position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);
                font-size: 48px; font-weight: bold; color: #FFD700;
                text-shadow: 2px 2px 4px rgba(0,0,0,0.8); z-index: 8000;
                pointer-events: none; font-family: monospace;
                animation: comboShow 1.5s ease-out;
            `;
            comboDisplay.textContent = `${this.comboCount}x 连击!`;
            
            const style = document.createElement('style');
            style.textContent = `
                @keyframes comboShow {
                    0% { opacity: 0; transform: translate(-50%, -50%) scale(0.5); }
                    50% { opacity: 1; transform: translate(-50%, -50%) scale(1.2); }
                    100% { opacity: 0; transform: translate(-50%, -50%) scale(1); }
                }
            `;
            document.head.appendChild(style);
            document.body.appendChild(comboDisplay);
            
            setTimeout(() => {
                if (comboDisplay.parentNode) document.body.removeChild(comboDisplay);
                if (style.parentNode) document.head.removeChild(style);
            }, 1500);
        }
        
        giveComboReward() {
            console.log(`🏆 连击奖励: ${this.comboCount}x`);
            
            // 生命值奖励
            if (window.player && window.player.health < window.player.maxHealth) {
                window.player.health = Math.min(window.player.maxHealth, window.player.health + 15);
                if (window.player.updateHealthUI) window.player.updateHealthUI();
                
                // 显示奖励
                const reward = document.createElement('div');
                reward.style.cssText = `
                    position: fixed; top: 30%; left: 50%; transform: translateX(-50%);
                    font-size: 24px; color: #00FF00; font-weight: bold;
                    text-shadow: 2px 2px 4px rgba(0,0,0,0.8); z-index: 8000;
                    pointer-events: none; font-family: monospace;
                    animation: rewardShow 2s ease-out;
                `;
                reward.textContent = '+15 生命值!';
                
                const style = document.createElement('style');
                style.textContent = `
                    @keyframes rewardShow {
                        0% { opacity: 1; transform: translateX(-50%) translateY(0); }
                        100% { opacity: 0; transform: translateX(-50%) translateY(-50px); }
                    }
                `;
                document.head.appendChild(style);
                document.body.appendChild(reward);
                
                setTimeout(() => {
                    if (reward.parentNode) document.body.removeChild(reward);
                    if (style.parentNode) document.head.removeChild(style);
                }, 2000);
            }
        }
        
        setupGameIntegration() {
            console.log('🔗 设置游戏集成');
            
            if (!window.gameEngine) {
                console.log('⚠️ 游戏引擎未准备就绪，稍后重试');
                setTimeout(() => this.setupGameIntegration(), 2000);
                return;
            }
            
            // 监控僵尸击杀
            this.lastZombieCount = window.gameEngine.zombies?.length || 0;
            
            setInterval(() => {
                if (window.gameEngine && window.gameEngine.zombies) {
                    const currentCount = window.gameEngine.zombies.length;
                    if (currentCount < this.lastZombieCount) {
                        const kills = this.lastZombieCount - currentCount;
                        for (let i = 0; i < kills; i++) {
                            this.addKill();
                        }
                    }
                    this.lastZombieCount = currentCount;
                }
            }, 100);
            
            // 创建环境物品
            this.createEnvironmentObjects();
            
            // 集成渲染
            this.integrateRendering();
            
            console.log('✅ 游戏集成完成');
        }
        
        createEnvironmentObjects() {
            console.log('🌍 创建环境物品');
            
            this.environmentObjects = [];
            
            // 创建桌子
            for (let i = 0; i < 3; i++) {
                this.environmentObjects.push({
                    x: Math.random() * 600 + 200,
                    y: Math.random() * 400 + 200,
                    width: 40,
                    height: 30,
                    health: 2,
                    maxHealth: 2,
                    type: 'table',
                    destroyed: false
                });
            }
            
            // 创建爆炸桶
            this.environmentObjects.push({
                x: Math.random() * 500 + 250,
                y: Math.random() * 300 + 250,
                width: 25,
                height: 35,
                health: 1,
                type: 'barrel',
                destroyed: false
            });
            
            console.log(`✅ 创建了 ${this.environmentObjects.length} 个环境物品`);
            
            // 开始环境更新
            setInterval(() => {
                this.updateEnvironment();
            }, 50);
        }
        
        updateEnvironment() {
            if (!window.gameEngine || !window.gameEngine.bullets) return;
            
            // 检查子弹碰撞
            window.gameEngine.bullets.forEach((bullet, bulletIndex) => {
                this.environmentObjects.forEach(obj => {
                    if (!obj.destroyed && this.isColliding(bullet, obj)) {
                        // 移除子弹
                        window.gameEngine.bullets.splice(bulletIndex, 1);
                        
                        // 伤害物品
                        obj.health--;
                        console.log(`💥 击中 ${obj.type}, 剩余血量: ${obj.health}`);
                        
                        if (obj.health <= 0) {
                            obj.destroyed = true;
                            
                            if (obj.type === 'barrel') {
                                this.explodeBarrel(obj);
                            } else {
                                this.createDebris(obj);
                            }
                        }
                    }
                });
            });
        }
        
        explodeBarrel(barrel) {
            console.log('💥 爆炸桶爆炸！');
            
            // 屏幕闪烁
            const flash = document.createElement('div');
            flash.style.cssText = `
                position: fixed; top: 0; left: 0; width: 100%; height: 100%;
                background: rgba(255, 100, 0, 0.5); pointer-events: none;
                z-index: 6000; animation: explosionFlash 0.5s ease-out;
            `;
            
            const style = document.createElement('style');
            style.textContent = `
                @keyframes explosionFlash {
                    0% { opacity: 0.7; }
                    100% { opacity: 0; }
                }
            `;
            document.head.appendChild(style);
            document.body.appendChild(flash);
            
            setTimeout(() => {
                if (flash.parentNode) document.body.removeChild(flash);
                if (style.parentNode) document.head.removeChild(style);
            }, 500);
            
            // 爆炸粒子
            if (window.gameEngine) {
                for (let i = 0; i < 12; i++) {
                    const angle = (Math.PI * 2 * i) / 12;
                    const speed = Math.random() * 200 + 100;
                    
                    window.gameEngine.particles.push({
                        x: barrel.x,
                        y: barrel.y,
                        vx: Math.cos(angle) * speed,
                        vy: Math.sin(angle) * speed,
                        life: Math.random() * 1 + 0.5,
                        maxLife: Math.random() * 1 + 0.5,
                        color: ['#FF4500', '#FF6347', '#FFD700'][Math.floor(Math.random() * 3)],
                        size: Math.random() * 8 + 4
                    });
                }
            }
        }
        
        createDebris(obj) {
            if (!window.gameEngine) return;
            
            // 碎片效果
            for (let i = 0; i < 5; i++) {
                window.gameEngine.particles.push({
                    x: obj.x + Math.random() * obj.width,
                    y: obj.y + Math.random() * obj.height,
                    vx: (Math.random() - 0.5) * 100,
                    vy: (Math.random() - 0.5) * 100,
                    life: 1,
                    maxLife: 1,
                    color: '#8B4513',
                    size: Math.random() * 4 + 2
                });
            }
        }
        
        integrateRendering() {
            console.log('🎨 集成渲染系统');
            
            // 保存原始渲染函数
            if (window.gameEngine && window.gameEngine.render) {
                const originalRender = window.gameEngine.render.bind(window.gameEngine);
                
                window.gameEngine.render = () => {
                    originalRender();
                    
                    // 渲染环境物品
                    this.renderEnvironment(window.gameEngine.ctx);
                    
                    // 渲染UI
                    this.renderGameUI(window.gameEngine.ctx);
                };
                
                console.log('✅ 渲染系统集成完成');
            }
        }
        
        renderEnvironment(ctx) {
            this.environmentObjects.forEach(obj => {
                if (obj.destroyed) return;
                
                ctx.save();
                
                if (obj.type === 'table') {
                    ctx.fillStyle = '#8B4513';
                    ctx.fillRect(obj.x, obj.y, obj.width, obj.height);
                    
                    if (obj.health < obj.maxHealth) {
                        ctx.fillStyle = '#654321';
                        ctx.fillRect(obj.x + 2, obj.y + 2, obj.width - 4, obj.height - 4);
                    }
                } else if (obj.type === 'barrel') {
                    ctx.fillStyle = '#DC143C';
                    ctx.fillRect(obj.x, obj.y, obj.width, obj.height);
                    ctx.fillStyle = '#FF6347';
                    ctx.fillRect(obj.x + 3, obj.y + 3, obj.width - 6, obj.height - 6);
                }
                
                ctx.restore();
            });
        }
        
        renderGameUI(ctx) {
            // 只在游戏中渲染
            if (window.gameEngine?.gameState !== 'playing') return;
            
            // 渲染连击
            if (this.comboCount > 0) {
                ctx.save();
                ctx.fillStyle = '#FFFFFF';
                ctx.font = 'bold 20px monospace';
                ctx.textAlign = 'center';
                ctx.shadowColor = 'rgba(0,0,0,0.8)';
                ctx.shadowBlur = 4;
                ctx.fillText(`${this.comboCount}x 连击`, 500, 80);
                ctx.restore();
            }
        }
        
        // 工具函数
        isColliding(obj1, obj2) {
            const o1 = {
                x: obj1.x - (obj1.radius || 5),
                y: obj1.y - (obj1.radius || 5),
                width: (obj1.radius || 5) * 2,
                height: (obj1.radius || 5) * 2
            };
            
            return o1.x < obj2.x + obj2.width &&
                   o1.x + o1.width > obj2.x &&
                   o1.y < obj2.y + obj2.height &&
                   o1.y + o1.height > obj2.y;
        }
    }
    
    // 立即创建实例
    window.instantEffects = new InstantEffects();
    
    console.log('⚡ 立即效果系统已加载');
    
})();